import json
from math import floor
import os
import sys
sys.path.append(os.getcwd())

from network_form.utils_network import load_all_graphs, read_data
from network_form.config import data_path
from network_form.config import graphs_path

from Model import *

event_list, topic_dict, member_list, group_list = read_data(data_path, False)
all_graphs = load_all_graphs(graphs_path)

event_dict = dict()
member_dict = dict()

# 有些event的member and response的member id 不在member list里
for __m__ in member_list:
    member_dict[str(__m__['id'])] = __m__

for __e__ in event_list: 
    __member_and_response__ = __e__['member and response']
    __e__['member and response']=dict()
    for __m_id__ in __member_and_response__.keys():
        if (member_dict.__contains__(str(__m_id__))):
            __e__['member and response'][__m_id__] = __member_and_response__[__m_id__]
    event_dict[str(__e__['id'])] = __e__

def test_country_help_reject():
    predict_country = CountryModel()
    total_num = 0
    pass_num = 0
    for e in event_list:
        for m_id in e['member and response']:
            res = predict_country(e, member_dict[m_id])
            if res==0:
                total_num+=1
                if e['member and response'][m_id]=='no':
                    pass_num+=1
    # 正确率为rate: 0.402674007078254 预测结果并不准确
    # 当event和member不在同一个国家时, 60%的情况会同意event的邀请
    print('rate: {}'.format(pass_num/total_num), pass_num, total_num)

def test_lon_lat_help_reject():
    predictor = LonLatModel(LonLatDiffMeasure(120, 70))
    total_num = 0
    pass_num = 0
    for e in event_list:
        for m_id in e['member and response']:
            res = predictor(e, member_dict[m_id])
            if res==0:
                total_num+=1
                if e['member and response'][m_id]=='no':
                    pass_num+=1
    # 正确率为rate: 0.4757085020242915 预测结果并不准确
    # 即使当跨越半个地球，也有一半的人会同意event的邀请 并且跨越半个地球的情况只有500例，基数过小
    print('rate: {}'.format(pass_num/total_num), pass_num, total_num)


# test_country_help_reject()
# test_lon_lat_help_reject()

def make_dataset_time_line(event_list):
    sorted(event_list, key=lambda x:x['created_time'])
    train_len = floor(len(event_list) * 0.8)
    train_list = event_list[:train_len]
    test_list = event_list[train_len:]

    return train_list, test_list
    
train_list, test_list = make_dataset_time_line(event_list)

# def test_history_model():
#     predictor = HistoryModel(all_graphs, group_list)

#     total_num = 0
#     valid_num = 0

#     for e in event_list:
#         mr = e['member and response']
#         for m_id in mr:
#             total_num+=1
#             res = predictor(e, member_dict[m_id])
#             # print(res)
#             # print(res)
#             if res==1 and mr[m_id]=='yes':
#                 valid_num+=1
#             elif res==0 and mr[m_id]=='no':
#                 valid_num+=1
#             elif res==0.5 and (mr[m_id]=='maybe' or mr[m_id]=='waitlist'):
#                 valid_num+=1
    
#     print(valid_num, total_num)

# test_history_model()

def test_model(train_list, test_list, model):
    predictor = model

    total_num = 0
    TP_num = 0
    FP_num=0
    FN_num=0
    TN_num=0

    for e in test_list:
        mr = e['member and response']
        for m_id in mr:
            total_num+=1
            res = predictor(e, member_dict[m_id])
            if res==1 and mr[m_id]=='yes':
                TP_num+=1
            elif res==0 and mr[m_id]=='no':
                TN_num+=1
            elif res==1 and mr[m_id]=='no':
                FP_num+=1
            elif res==0 and mr[m_id]=='yes':
                FN_num+=1
    print("Accuracy: {}, Precision: {}, Recall: {}".format((TP_num+TN_num)/total_num, TP_num/(TP_num+FP_num), TP_num/(TP_num+FN_num)))

# test_model(train_list, test_list, HistoryModel(all_graphs, event_list, group_list, member_list))

# test_model(train_list, test_list, ClosestMemberModel(train_list, member_list, group_list, k1=5, k2=5))

test_model(train_list, test_list, YesTendencyModel(train_list, member_list, k=20))
# 假设知道别人是否接受event邀请, 根据别人的回复来确定是否参加
# test_model(train_list, test_list, OtherMemberModel(all_graphs, group_list, k=10))